1. Report with R Markdown - Theory
R Markdown is an authoring framework for data science (AFDS) combining R code with narrative text. AFDS permits to create a computational document, with a notebook interface for report generation. There are other AFDS like Jupyter in Python, D3.js and Plotly both in JavaScript.
| AFDS | Description | Description |
|---|---|---|
| Rmarkdown | R | front-end oriented |
| Jupyter | Python | back-end oriented |
| D3.js | JavaScript | web oriented |
| Plotly | JavaScript | web oriented |
R Markdown use Markdown syntax, supports HTML/CSS tags, BibTex bibliographic references, 3D charts. The main R Markdown packages are:
rmarkdown} dynamic documentknitr} designed to be a ‘transparent engine for dynamic report generation with R’ (Xie 2022)bookdown} advanced editing and publishing functionstinytex} for LaTeX syntaxIn RStudio:
File > New file > R Markdown...
The parameters (Title, Author) can be changed later on the YAML header
A new document is created:
Run the new document with knit
R Markdown combines:
a YAML header for the document metadata
different code chunks (R code embedded)
many narrative parts (Markdown syntax) with inline R code
|
YAML header |
|
narrative part |
|
R code |
|
narrative part |
|
R code |
|
… |
|
… |
Narrative parts required principally the use of the Markdown syntax, but also supports HTML/CSS code, LaTeX syntax, etc.
Markdown is an easy-to-write plain text syntax used by different code-oriented frameworks:
Markdown basic syntax
Markdown online editor
These coding give the same results (Markdown and HTML):
{width=500px}
<img align="center" src="https://raw.githubusercontent.com/zoometh/oxford/main/R4A/www/logo.png" alt="" width=500>
{width=500px}
<img align="center" src="www/logo.png" alt="" width=500>
# Header level 1
## Heading level 2
### Heading level 3
etc.
Avoid numbering of titles:
#### Spaces and end of lines {-}
Add an anchor
#### Bookmarks {-#bookmarks}
Extra spaces (HTML tags)
  means 4 spaces (= a tabulation)  means 2 spaces means 1 spaceEnd of line (<br> in HTML) with 2 or more spaces and return, for example:
'Reconnais-toi
Cette adorable personne c'est toi
Sous le grand chapeau canotier
Oeil
Nez
Ta Bouche
Voici l’ovale de ta figure
Ton cou Exquis' (Apollinaire, 1913)
‘Reconnais-toi
Cette adorable personne c’est toi
Sous le grand chapeau canotier
Oeil
Nez
Ta Bouche
Voici l’ovale de ta figure
Ton cou Exquis’ (Apollinaire, 1913)
| code in R Markdown | Output |
|---|---|
**bold**, __bold__ |
bold, bold |
*italic*, _italic_ |
italic, italic |
code |
code |
hyphen -- inserted -- in a sentence |
hyphen – inserted – in a sentence |
H~2~O |
H2O |
10^−19^ |
10−19 |
$$\sum_{i=1}^{n} X^3_i$$ |
\[\sum_{i=1}^{n} X^3_i\] |
| … | … |
>> I am commented
I am commented
--- or ***
A extended part of the text styling can also be done with HTML/CSS
- numbered
1. first element
2. second element
3. third element
numbered
- bullet
* first element
* second element
* third element
- third element - sub 1
- third element - sub 2
+ third element - sub 2 - subsub 1
+ third element - sub 2 - subsub 2
bullet
| Syntax | Description |
| --- | ----------- |
| Header | Title |
| Paragraph | Text |
and
| Syntax | Description |
| ----------- | ----------- |
| Header | Title |
| Paragraph | Text |
produce the same result:
| Syntax | Description |
|---|---|
| Header | Title |
| Paragraph | Text |
| Left | Center | Rigth |
| :--- | :----: | ---: |
| Header | Title | Here's this |
| Paragraph | Text | And more |
| Left | Center | Rigth |
|---|---|---|
| Header | Title | Here’s this |
| Paragraph | Text | And more |
Table are often data structure difficult to layout. For complex tables you will need to use code chunks, e.g. kable() from {knitr} with kable_styling() from {kableExtra}
Report with R Markdown, part 2: [Practice](https://zoometh.github.io/oxford/R4A/2_R Markdown_Practice)
Report with R Markdown, part 2: Practice
[{width=70px}](https://www.unipi.it/index.php/humanities/item/16574-r4rchaeologists)
Hyperlinks can also be done with HTML/CSS
After this theoretical part, you will have to [practice](#practice)
After this theoretical part, you will have to practice
The reference section, ‘Practice,’ appears like that:
Add footnote to the bottom of the document
A simple footnote,[^1] or a longer one.[^bignote]
A simple footnote,1 or a longer one.2
[^1]: This is the first footnote.
[^bignote]: Here's one with multiple paragraphs and code.
Indent paragraphs to include them in the footnote.
`{ my code }`
Add as many paragraphs as you like.
Cite and reuse variables, figures, tables, sections, etc., through your document
In the following verbatim parts, replace
library(archdata)
data("Handaxes")
number.of.axes <- nrow(Handaxes)
'(...) the Furze Platt dataset counts 'r number.of.axes' described by 'r ncol(Handaxes)'. The maximal length (L = 'r max(Handaxes$L)') (...)'
‘(…) the Furze Platt dataset counts 600 described by 8. The maximal length (L = 242) (…)’
library(archdata)
data("Handaxes")
plot(Handaxes$L, Handaxes$B)
model <- lm(B ~ L, data = Handaxes)
abline(lm(model))
Figure 2.1: Maximum Length/Maximum breadth in cm
'(...) the distribution of the maximum length (L) and maximum breadth (B) shows a R^2^ = 'r round(model$coefficients[2], 2)', Fig. \@ref(fig:maxLmaxB)) (...)'
‘(…) the distribution of the maximum length (L) and maximum breadth (B) shows a R2 = 0.42, Fig. 2.1) (…)’
See section [**Bookmarks**](#bookmarks)
See section Bookmarks
.bib referenced in the YAML header| code in R Markdown | Output |
|---|---|
@Xie22 |
Xie (2022) |
[@Xie22] |
(Xie 2022) |
[credits: @Xie22] |
(credits: Xie 2022) |
published by Yihui Xie [-@Xie20; -@Xie22] |
published by Yihui Xie (2020; 2022) |
| … | … |
Bibliographies and citations (Xie, Dervieux, and Riederer 2020)
Code chunks, or chunks, are the placeholders for the coding part of the document
The chunk header is used to set the output results parameters (show code, size of the output image, etc.)
run the previous chunks but not this one
run this chunk
Code evaluation
include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks.
echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
message = FALSE prevents messages that are generated by code from appearing in the finished file.
warning = FALSE prevents warnings that are generated by code from appearing in the finished.
Parameters of the graphical results
fig.cap = "..." adds a caption to graphical results.
fig.height = 7 height to use in R for plots created by the chunk (in inches)
fig.width = 7 width to use in R for plots created by the chunk (in inches)
fig.align = default how to align graphics in the final document. One of ‘left,’ ‘right,’ or ‘center’
The first top chunk (the first one in the document) can set these parameters for all other chunks, e.g. knitr::opts_chunk$set(echo = TRUE) will ‘echoing’ all chunks
The body of a code chunk is
This is the YAML header, it contains the metadata and the document configuration.
title: Title
author: Author
date:
"'r format(Sys.time(), '%D')'""'r format(Sys.time(), '%d %B %Y')'"toc: table of contents
bibliography: bibliographical references, BibTex format (e.g. https://github.com/zoometh/oxford/blob/main/R4A/references.bib)
etc.
Can be use in all parts of the document (YAML header, code chunks, narrative parts)
| code in R Markdown (= HTML) | Output |
|---|---|
<span style='font-size: 30px'>Big font</span> |
Big font |
<b>bolded</b> |
bolded |
<span style="color:red">color</span> |
color |
| … | … |
Customize the document with CSS layouts like <notes>this CSS element with a dodgerblue for background and white for text</notes> here: https://github.com/zoometh/oxford/blob/main/R4A/styles.css
Customize the document with CSS layouts like
The CSS file is here: https://github.com/zoometh/oxford/blob/main/R4A/styles.css
CSS online editor, e.g. fonts
The interest of HTML is its ability to be deployed online, with interactive settings. R offers a real framework to create interactive documents, Shiny. Shiny can be integrated into R Markdown
File > New File > Rmarkdown > Shiny, or runtime: shiny`
With the {leaflet} package
library(dplyr)
library(leaflet)
munsingen.long <- 7.569587484129203
munsingen.lat <- 46.864709895956004
leaflet(width = "60%", height = "400px") %>%
addTiles(group = 'OSM') %>%
addControl("Munsingen necropolis", position = "bottomright") %>%
addProviderTiles(providers$Esri.WorldImagery, group='Esri.WorldImagery') %>%
addMarkers(munsingen.long,
munsingen.lat,
label = "Munsingen necropolis") %>%
addLayersControl(
baseGroups = c('OSM', 'Esri.WorldImagery')) %>%
addScaleBar(position = "bottomleft")
With the {plotly} package
Export R Markdown in:
out_put: pdf_document
keep_tex: true
Exists a lot of online apps making the conversions easier: Pandoc converter, Word to HTML, etc.
?archdata to see the list of these dataset)